from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from app.database import SessionLocal
from app.models.order import Order
from app.models.spot import Spot
from pytz import timezone

_scheduler = None  # 全局变量存储调度器实例

def cancel_timeout_orders():
    """取消超时未支付的订单"""
    db = SessionLocal()
    try:
        beijing_tz = timezone('Asia/Shanghai')
        now = datetime.now(beijing_tz)
        
        # 查找所有超时的待支付订单
        timeout_orders = (
            db.query(Order)
            .filter(
                Order.status == "pending",
                Order.expires_at <= now
            )
            .all()
        )
        
        # 取消订单并恢复库存
        for order in timeout_orders:
            # 恢复景点库存
            spot = db.query(Spot).filter(Spot.id == order.spot_id).first()
            if spot:
                spot.inventory += order.quantity
            
            # 更新订单状态
            order.status = "cancelled"
        
        db.commit()
        print(f"已取消 {len(timeout_orders)} 个超时订单")
        
    except Exception as e:
        print(f"取消超时订单时出错: {str(e)}")
        db.rollback()
    finally:
        db.close()

def init_scheduler():
    """初始化定时任务"""
    global _scheduler
    if _scheduler is None:  # 只有在调度器不存在时才创建
        _scheduler = BackgroundScheduler()
        
        # 添加定时任务，每小时检查一次
        _scheduler.add_job(
            cancel_timeout_orders,
            trigger=IntervalTrigger(hours=1),
            id='cancel_timeout_orders',
            name='取消超时订单',
            replace_existing=True
        )
        
        # 启动调度器
        _scheduler.start()
    return _scheduler 